//
//  LGOAuthViewController.m
//  微博
//
//  Created by MS on 15-12-5.
//  Copyright (c) 2015年 MS. All rights reserved.
//

#import "LGOAuthViewController.h"
#import "MBProgressHUD+MJ.h"

#import "LGAccount.h"
#import "LGAccountTool.h"
#import "LGRootTool.h"


#define LGOAuthauthorizeBaseUrl @"https://api.weibo.com/oauth2/authorize"
//#define LGclient_id     @"1440935985"
//#define LGredirect_uri  @"http://sns.whalecloud.com/sina2" //http://sns.whalecloud.com/sina2/callback

@interface LGOAuthViewController ()<UIWebViewDelegate>

@end

@implementation LGOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //展示网页-->UIwebView
    UIWebView * webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:webView];
    
    //加载网页
    //创建url https://api.weibo.com/oauth2/authorize?client_id=1440935985&redirect_uri=http://www.baidu.com
    
    NSString * urlStr = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",LGOAuthauthorizeBaseUrl,LGclient_id,LGredirect_uri];
    
    NSURL * url = [NSURL URLWithString:urlStr];
    
    //创建请求
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    //加载请求
    [webView loadRequest:request];
    
    //设置代理
    webView.delegate = self;
}

#pragma webView 代理
//开始加载
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    //提示用户正在加载
    [MBProgressHUD showMessage:@"正在加载..."];
    
    
}
//完成加载
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    [MBProgressHUD hideHUD];
    
}

//加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
    [MBProgressHUD hideHUD];
    
}

//拦截webView请求
//当webView需要加载一个请求，调用该方法询问
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString  * urlstr = request.URL.absoluteString;
    
    //获取code(RequestToken)
    NSRange range = [urlstr rangeOfString:@"code="];
    if (range.length ) {
        
        NSString * codeStr = [urlstr substringFromIndex:range.location+range.length];
        
       // LGLog(@"%@\n%@",urlstr,codeStr);
        
       //换取accessToken
        [self accessTokenWithCode:codeStr];
        
        //不回调页面
        return NO;
    }
    
    return YES;
}

/*
 
 必选	类型及范围	说明
 client_id	true	string	申请应用时分配的AppKey。
 client_secret	true	string	申请应用时分配的AppSecret。
 grant_type	true	string	请求的类型，填写authorization_code
 
 grant_type为authorization_code时
 必选	类型及范围	说明
 code	true	string	调用authorize获得的code值。
 redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
 

// error---->Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain" UserInfo=0x7f9d7c852b70

    content-type为响应头内容的类型

     "access_token" = "2.00CnYaJCzQBWZB1e189662bbOczERD";
     "expires_in" = 157679999;
     "remind_in" = 157679999;
     uid = 1973966232;
 */

-(void)accessTokenWithCode:(NSString *)code
{
    
    [LGAccountTool accessTokenWithCode:code success:^{
        //进入主页或新特性页面，选择窗口根控制器
        [LGRootTool chooseRootViewController:LGKeyWindow];
        
    } failure:^(NSError *error) {
        
    }];
       
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
